package bma.common.langutil.ai.vm;

import bma.common.langutil.concurrent.ProcessQueue;
import bma.common.langutil.concurrent.ProcessThread;

public class AIThreadImpl implements AIThread {

	protected final AIVM vm;
	protected final ProcessThread core;
	protected final int id;

	public AIThreadImpl(AIVM vm, int id) {
		this.vm = vm;
		this.id = id;
		core = new ProcessThread(vm.getThreadGroup(), vm.getName() + id,
				vm.getStackSize(), new ProcessQueue()) {
			@Override
			public void run() {
				AIVM.local.set(AIThreadImpl.this);
				try {
					super.run();
				} finally {
					AIVM.local.set(null);
				}
			}
		};
	}

	@Override
	public void wakup() {
		core.wakup();
	}

	@Override
	public AIVM getVM() {
		return vm;
	}

	@Override
	public int getThreadId() {
		return id;
	}

	@Override
	public void execute(Runnable command) {
		core.postIntent(command);
	}

	public int load() {
		return core.getCore().load();
	}

}
